package com.bxl.chooser.client;

import com.bxl.chooser.bean.ChooseResponseMsg;
import com.bxl.netty.rpc.common.context.Context;
import com.bxl.netty.rpc.common.message.MsgResponseContent;
import com.bxl.netty.rpc.common.message.PackageMsg;
import com.bxl.netty.rpc.common.message.RpcHeader;
import com.bxl.netty.rpc.common.serialize.Serialize;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * <>
 *
 * @author baixl
 * @date 2021/2/23
 */
public class ChooseClientMsgDecoder extends ByteToMessageDecoder {
    private final static int HEADER_LENGTH = 16;// header的长度
    private Context context;
    private Serialize serialize;

    public ChooseClientMsgDecoder() {

    }

    public ChooseClientMsgDecoder(Context context) {
        assert context == null;
        this.context = context;
        this.serialize = this.context.getSerialize();
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 长度不足，退出
        if (in.readableBytes() < HEADER_LENGTH) {
            return;
        }
        PackageMsg<ChooseResponseMsg> registerPackageMsg = new PackageMsg<ChooseResponseMsg>();
        // 获取协议的版本
        int flag = in.readInt();
        // 获取消息长度
        long requestID = in.readLong();
        registerPackageMsg.setHeader(new RpcHeader(flag, requestID));
        int length = in.readInt();
        if(length == 0){
            registerPackageMsg.setContent(null);
        }else{
            if (in.readableBytes() < length) {
                in.setIndex(in.readerIndex() - HEADER_LENGTH, in.writerIndex());
                return;
            }
            byte[] content = new byte[length];
            in.readBytes(content);
            //MsgResponseContent msgResponseContent = this.serialize.deserialize(content);
            registerPackageMsg.setContent((ChooseResponseMsg)this.serialize.deserialize(content));
        }

        out.add(registerPackageMsg);
    }
}
